package com.bluesky.jwf.util.state;

import javax.servlet.http.HttpServletRequest;

import com.bluesky.jwf.component.Page;
import com.bluesky.jwf.component.window.MainWindow;
import com.bluesky.jwf.util.JWFServlet;
import com.bluesky.jwf.util.ResourceUtil;
import com.bluesky.jwf.util.ServletContext;

public class FileStateHandler extends AbstractStateHandler implements
		StateHandler {
	public static String STATE_FILE_NAME_IN_SESSION = "_jwf_state_file_name_in_session";

	public static String STATE_FOLDER = "state.folder";

	private String stateFolder;

	@Override
	public void setParameter(String key, String value) {

		if (STATE_FOLDER.equals(key))
			stateFolder = value;
	}

	@Override
	public Object get(HttpServletRequest req, ServletContext context) {
		String windowFileName = (String) req.getSession().getAttribute(
				STATE_FILE_NAME_IN_SESSION);
		Object obj = null;
		if (windowFileName != null)
			obj = ResourceUtil.readObjectFromFile(windowFileName);

		return obj;
	}

	@Override
	public void store(HttpServletRequest req, MainWindow window, Page page) {
		String fileName = stateFolder + req.getSession().getId();
		ResourceUtil.writeObjectToFile(window, fileName);
		req.getSession().setAttribute(STATE_FILE_NAME_IN_SESSION, fileName);
	}

	public String getStateFolder() {
		return stateFolder;
	}

	public void setStateFolder(String stateFolder) {
		this.stateFolder = stateFolder;
	}

}
